//
//  SSWBMainViewController.swift
//  shanshanlol微博
//
//  Created by 叶竞泽 on 2017/1/7.
//  Copyright © 2017年 JingZe. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 主控制器
class SSWBMainViewController: UITabBarController {
    
    /// 定时器
    fileprivate var timer: Timer?
    
    /// 使用代码控制设备的方向，可以在需要横屏的时候，单独处理。设置方向后，所有子控制器都遵守这个设置。如果播放视频，通畅是modal展现的
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return [.portrait]
    }
    // MARK: - 监听方法
    
    /// 撰写微博
    @objc fileprivate func composeStatus() {
        
        // FIXME
        // 1.判断是否登录
        
        // 2.实例化视图
        let v = SSWBComposeTypeView.composeTypeView()
        // 3.显示视图 - 注意闭包的循环引用
        v.show {[weak v] (clsName) in
            guard let className = clsName, let vc = NSClassFromString(Bundle.main.namespace + "." + className) as? UIViewController.Type else {
                v?.removeFromSuperview()
                return
            }
            let controller = vc.init()
            let nav = UINavigationController(rootViewController: controller)
            self.present(nav, animated: true, completion: {
                v?.removeFromSuperview()
            })
        }
    }
    
    @objc private func userLogin(notification: Notification) {
        print("用户登录通知:\(notification)")
        
        var when = DispatchTime.now()
        
        // 判断notification.object是否有值,提示用户重新登录
        
        if notification.object != nil {
            when = DispatchTime.now() + 2
            SVProgressHUD.showInfo(withStatus: "用户登录已经超时,需要重新登录")
        }
        
        DispatchQueue.main.asyncAfter(deadline: when) {
            // 展现登录控制器,通常配合NavigationController一起使用
            let vc = SSWBOAuthViewController()
            let nav = UINavigationController(rootViewController: vc)
            self.present(nav, animated: true, completion: nil)
        }
    }
    
    // MARK: - 私有控件
    
    // 撰写按钮
    fileprivate lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    // MARK: - 生命周期
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 设置tabbar文字颜色渲染
        tabBar.tintColor = UIColor.orange
        setupChildControllers()
        setupComposeButton()
        setupTimer()
        
        // 设置新特性视图
        setupNewFeatureViews()
        
        // 设置代理
        delegate = self
        
        // 注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin(notification:)), name: NSNotification.Name(WBUserShouldLoginNotification), object: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    /// 释放资源
    deinit {
        // 销毁时钟
        timer?.invalidate()
        // 销毁通知
        NotificationCenter.default.removeObserver(self)
    }
    
}

// MARK: - 设置新特性视图
extension SSWBMainViewController {
    
    fileprivate func setupNewFeatureViews() {
        
        // 1.如果有更新,显示新特性,如果没有更新,显示欢迎
        if !SSWBNetworkManager.shared.userLogon {
            return
        }
        
        let v = hasNewVersion ? SSWBNewFeatureView.newFeatureView() : SSWBWelcomeView.welcomeView()
        
        // 2.添加视图
        view.addSubview(v ?? view)
    }
    
    /// extension中可以有计算性属性,这种属性不占用存储空间
    private var hasNewVersion: Bool {
        
        // 1.取出当前的版本号 1.0.1
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        
        // 2.取出保存在document中的之前的版本号 ""
        let path = ("version" as NSString).cz_appendDocumentDir() as NSString
        let sandboxVersion = try? String(contentsOfFile: path as String)
        print("沙盒版本\(sandboxVersion)")
        
        // 3.将当前版本号保存在沙盒 1.0.1
        _ = try? currentVersion.write(toFile: path as String, atomically: true, encoding: String.Encoding.utf8)
        
        // 4.返回版本号是否一致 new
        return currentVersion != sandboxVersion
    }
}

// MARK: - 设置UITabBarControllerDelegate
extension SSWBMainViewController: UITabBarControllerDelegate {
    
    /// 将要选择的tabBarItem
    ///
    /// - Parameters:
    ///   - tabBarController: tabBarController
    ///   - viewController: 目标控制器
    /// - Returns: 是否切换
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        
        /// 即将跳转的索引
        let index = (childViewControllers as NSArray).index(of: viewController)
        
        // 判断当前是不是首页和是否在重复点击首页
        if selectedIndex == index && selectedIndex == 0{
            
            // 刷新首页
            // 1.获取到控制器
            let homeVC = (viewController as? UINavigationController)?.topViewController as? SSWBHomeViewController
            // 2.表格回滚到顶部
            homeVC?.tableView?.setContentOffset(CGPoint(x: 0, y: 0 - 64), animated: true)
            
            // 3.刷新表格
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                homeVC?.loadData()
                homeVC?.tableView?.setContentOffset(CGPoint(x: 0, y: 0 - 64), animated: true)
            })
            
            // 4.重置badage
            homeVC?.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
            
            return false
            
        } else {

            return true
        }
    }
}

// MARK: - 时钟相关方法
extension SSWBMainViewController {
    
    /// 准备时钟
    fileprivate func setupTimer() {
        
        // 每30秒执行一次,时间间隔建议长一些
        timer = Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    /// 时钟触发方法
    @objc private func updateTimer() {
        
        // 如果没有登录,就不继续处理时钟
        if  !SSWBNetworkManager.shared.userLogon {
            return
        }
        
        SSWBNetworkManager.shared.unreadCount { (count) in
            // 设置首页tabbarItem的badge数量
            print(count)
            self.childViewControllers.first?.tabBarItem.badgeValue = count > 0 ? "\(count)" : nil
            // 设置app的badge,iOS 8 之后需要用户授权才可以使用
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}

// MARK: - 设置界面
extension SSWBMainViewController {
    
    /// 设置撰写按钮
    fileprivate func setupComposeButton() {
        // 添加按钮到tabar
        tabBar.addSubview(composeButton)
        // 设置按钮的位置
        let count = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width / count
        // 正数向内缩进,负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: w * 2, dy: 0)
        // 添加监听方法
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    /// 设置所有子控制器
    fileprivate func setupChildControllers() {
        
        // 从沙盒加载json
        let docDir = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first!
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        // 加载data
        var data = NSData(contentsOfFile: jsonPath)
        
        // 判断data是否有内容,如果没有,说明路径不存在
        if data == nil {
            // 从bundle加载data
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        
        // data一定有内容
        // 从bundle加载配置的json
        guard let array = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as? [[String: Any]] else {
            return
        }
        // 遍历数组,循环创建控制器
        var arrayM = [UIViewController]()
        
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        
        // 设置TabBar的子控制器
        viewControllers = arrayM
    }
    
    /// 使用字典创建子控制器
    ///
    /// - Parameter dict: 字典信息[clsName, title, imageName]
    /// - Returns: 子控制器
    private func controller(dict: [String: Any]) -> UIViewController {
        // 1.取得字典内容
        guard let clsName = dict["clsName"] as? String, let title = dict["title"] as? String, let image = dict["imageName"] as? String, let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? SSWBBaseViewController.Type, let visitorDict = dict["visitorInfo"] as? [String: String] else {
            return UIViewController()
        }
        // 2.创建视图控制器
        let vc = cls.init()
        // 设置title
        vc.title = title
        // 设置图像
        vc.tabBarItem.image = UIImage(named: "tabbar_" + image)?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + image + "_selected")?.withRenderingMode(.alwaysOriginal)
        // 设置控制器的访客信息字典
        vc.visitorInfoDictionary = visitorDict
        
        // 实例化导航控制器的时候会自动push
        let nav = SSWBNavigationController(rootViewController: vc)
        return nav
    }
}
